package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService paramService;

    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }


    @Override
    public List<SpecGroupDTO> querySpecs(Long categoryId) {
        // 1.根据分类id查询规格组的集合， SELECT * from tb_spec_group WHERE category_id = 76
        List<SpecGroup> groupList = query().eq("category_id", categoryId).list();
        // 2.把groupList转换为DTO
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(groupList);

        // 3.查询所有的参数
        List<SpecParamDTO> paramDTOList = paramService.queryParams(categoryId, null, null);
        // 4.把参数根据groupId分组，groupId一致的存入一个集合中，然后放入map，Map的key是groupId，值就是param集合
        // Map<Long, List<SpecParamDTO>> map = paramDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        Map<Long, List<SpecParamDTO>> map = new HashMap<>(groupDTOList.size());
        for (SpecParamDTO paramDTO : paramDTOList) {
            if(!map.containsKey(paramDTO.getGroupId())){
                map.put(paramDTO.getGroupId(), new ArrayList<>());
            }
            map.get(paramDTO.getGroupId()).add(paramDTO);
        }

        // 5.遍历组的集合
        for (SpecGroupDTO groupDTO : groupDTOList) {
            // 获取groupId
            Long groupId = groupDTO.getId();
            // 把params存入groupDTO
            List<SpecParamDTO> params = map.get(groupId);
            // 存入DTO
            groupDTO.setParams(params);
        }
        return groupDTOList;
    }


   /* @Override
    public List<SpecGroupDTO> querySpecs(Long categoryId) {
        // 1.根据分类id查询规格组的集合， SELECT * from tb_spec_group WHERE category_id = 76
        List<SpecGroup> groupList = query().eq("category_id", categoryId).list();
        // 2.把groupList转换为DTO
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(groupList);

        // 3.根据组的id，查询规格参数集合
        for (SpecGroupDTO groupDTO : groupDTOList) {
            List<SpecParamDTO> params = paramService.queryParams(null, groupDTO.getId(), null);
            // 把params存入groupDTO
            groupDTO.setParams(params);
        }
        return groupDTOList;
    }*/
}